<template>
  <div :id="config.id" class="wu-uploader"></div>
</template>

<script>
import api from 'src/plugins/http/api';
import store from 'src/store';
import { showLoading , msgFn } from 'src/utils';


let chunkSize = 10 * 1024 * 1024;
let fileInfo = {
    'name': [],
    chunkSize,
    'hash':[],
    'fileSize':[],
    'num':0
};
let successNum = 0;
const {state} = store;
const paramsReset = () =>{
    fileInfo = {
        'name': [],
        chunkSize,
        'hash':[],
        'fileSize':[],
        'num':0
    };
    successNum = 0;
};
let loadingInstance = null;

export default {
    'props':{
        'config':{
            'type':Object,
            'default':()=>({
                'id':'uploader'
            })
        }
    },
    data(){
        return {
            'options':{
                // swf文件路径
                'swf': '/lib/webuploader-0.1.5/Uploader.swf',
                // 文件接收服务端。
                'server': api.uploadSend,
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                'pick': {
                    'id': '#picker',
                    'multiple': true
                },
                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                'resize': false,
                // 开起分片上传。
                'chunked': true,
                chunkSize,
                'duplicate': false,
                'threads': 3, //上传并发数
                'formData': {
                    'secret': state.userInfo.secret
                },
                'headers':{
                    'appkey': 'a33a1726d93a401b812bafff8d5b73c3',
                    'secret': state.userInfo.secret
                },
                // 'fileNumLimit':5,
                'accept': [
                    {
                        'title': 'Images',
                        'extensions': 'gif,jpg,jpeg,bmp,png',
                        'mimeTypes': 'image/*'
                    }
                ]
            }
        };
    },
    mounted(){
        this.reset();
    },
    'methods':{
        createUpload(){
            const _self = this;
            this.uploader = WebUploader.create(this.options);
            this.uploader.on('beforeFileQueued', file => {
                if (_self.options.formData.accept.indexOf(file.ext)===-1){
                    msgFn('文件上传格式不正确');
                    return false;
                }
                _self.$emit('beforeFileQueued',file);
            });
            // 当有文件被添加进队列的时候
            this.uploader.on('fileQueued', file => {
                fileInfo.num+=1;
                _self.$emit('fileQueued',file);
            });
            // 当有文件被移除队列的时候
            this.uploader.on('fileDequeued', file => {
                fileInfo.num-=1;
                _self.$emit('fileDequeued',file);
            });
            // 文件上传过程中创建进度条实时显示。
            this.uploader.on('uploadProgress', (file, percentage) => {
                _self.$emit('uploadProgress',{file,percentage});
            });
            //单个文件开始上传
            this.uploader.on('uploadStart', (file, percentage) => {
                // console.log(percentage);
            });
            this.uploader.on('uploadSuccess', (file,res) => {
                successNum +=1;
                fileInfo.hash.push(res.data.hash);
                fileInfo.name.push(file.name);
                fileInfo.fileSize.push(file.size);
                if (successNum === fileInfo.num){
                    _self._uploadSuccess();
                }
            });
            this.uploader.on('uploadFinished', () =>{
                _self.uploader.reset();
            });
        },
        uploaderStart(){
            loadingInstance = showLoading({});
            this.uploader.upload();
        },
        removeFile(file){
            this.uploader.removeFile(file.id);
        },
        _uploadSuccess(){
            const _self = this;
            $.ajax({
                'type': 'post',
                'url': api.uploadSuccess,
                'data': JSON.stringify(fileInfo),
                'contentType': 'application/json',
                'headers':{
                    'appkey': 'a33a1726d93a401b812bafff8d5b73c3',
                    'secret': state.userInfo.secret
                },
                'success': function (res) {
                    const nData=[];
                    res.data.forEach(d => {
                        nData.push(d.replace(/http:\/\/192\.168\.1\.74:8848/,`http://${window.location.host}`));
                    });
                    res.data = nData;
                    paramsReset();
                    _self.$emit('uploadSuccess', res);
                },
                'complete': function () {
                    if (loadingInstance){ loadingInstance.close(); }
                }
            });
        },
        reset(){
            this.$nextTick(()=>{
                const {id,options} = this.config;
                this.options = $.extend(true,this.options,options);
                this.options.formData.accept=this.options.accept.map(acc=>acc?.extensions).join(',');
                const {pick} = this.options;
                $(`#${id || 'uploader'}`).empty().html(`<div class=btns><div id=${pick.id.replace(/#/ig,'')}>选择文件</div></div>`);
                this.createUpload();
            });
        }
    }
};
</script>

<style scoped lang="less">
  .wu-uploader{
    line-height: 20px;
    height: 40px;
  }
</style>
